<template>
  <div class="write-article-container">
      <h2 class="section-title">写文章</h2>
      <input v-model="article.title" type="text" placeholder="文章标题" />
      <input v-model="article.introduction" type="text" placeholder="文章简介" />
      <input v-model="article.tag" type="text" placeholder="文章标签，多个标签用逗号分隔" />
      <vue-markdown-editor v-model="markdownContent" ref="mdEditor" />
      <button class="capsule-btn" @click="saveDraft">保存草稿</button>
      <button class="capsule-btn" @click="publishArticle">发布文章</button>
  </div>
</template>

<script>
import axios from 'axios';
import VueMarkdownEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js';
import '@kangc/v-md-editor/lib/theme/style/vuepress.css';

VueMarkdownEditor.use(vuepressTheme);

export default {
  components: {
      VueMarkdownEditor
  },
  data() {
      return {
          article: {
              title: '',
              introduction: '',
              tag: '',
              status: '草稿',
              content: ''
          },
          markdownContent: ''
      };
  },
  methods: {
      async saveDraft() {
          this.article.status = '草稿';
          this.article.content = this.markdownContent;
          try {
              const response = await axios.post('/article/saveDraft', this.article);
              if (response.data.code === 200) {
                  alert('草稿保存成功');
              } else {
                  alert('草稿保存失败');
              }
          } catch (error) {
              console.error('保存草稿出错', error);
          }
      },
      async publishArticle() {
          this.article.status = '已发布';
          this.article.content = this.markdownContent;
          try {
              const response = await axios.post('/article/create', this.article);
              if (response.data.code === 200) {
                  alert('文章发布成功');
              } else {
                  alert('文章发布失败');
              }
          } catch (error) {
              console.error('发布文章出错', error);
          }
      }
  }
};
</script>